﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using nwrole.toolbox.sync.entity;
using nwrole.toolbox.sync.contract;
using System.Data.SqlClient;
using BLToolkit.Data.DataProvider;
using nwrole.toolbox.sync;
using System.ServiceModel;

namespace sync_source_console
{
    /*public class SourceService : ISyncSourceService
    {

        public string SyncOnce(long id)
        {
            var rep = GetRepository();
            var entity = rep.FindByIdWithRef(id);
            System.Console.WriteLine("Sync " + entity.Name + ":");
            GhostTableSync sync = GetGhostTableSync(100000);

            EndpointAddress ep = new EndpointAddress("http://localhost:9004/hejsan.svc");
            ISyncDestinationService destinationService = ChannelFactory<ISyncDestinationService>.CreateChannel(new BasicHttpBinding(), ep);

            syncTable(100000, entity, sync, destinationService);
            return null;
        }

        private SyncResult syncTable(int batchSize, SyncEntity map, GhostTableSync sync, ISyncDestinationService destinationService)
        {
            try
            {
                Guid guid = Guid.NewGuid();
                int messageCounter = 0;
                var result = sync.SyncWithReaderAndDirectUpdate(map, (bytes, tableName, schema) =>
                {
                    SyncMessageEnvelope msg = new SyncMessageEnvelope(tableName, "ibbe3", bytes, schema, guid);
                    destinationService.ProcessMessageOld(msg);
                    messageCounter++;
                    return 1;
                });
                Console.Write(result.RowCount);

                //if ((result != null) && (result.newSyncDat.HasValue)) {
                //    map.SyncDat = result.newSyncDat.Value;
                //}
                //SyncEntity.Update(map, SyncSettings.SrcConnectionString);
                

                SyncCompleteEnvelope completetMsg = new SyncCompleteEnvelope();
                completetMsg.MsgCorr = guid;
                completetMsg.DestinationSyncCompleteSPName = map.DestinationSyncCompleteSPName;
                completetMsg.MessageCount = messageCounter;

                try
                {
                    destinationService.SyncComplete(completetMsg);

                    if ((result != null) && (result.newSyncDat.HasValue))
                    {
                        map.SyncDat = result.newSyncDat.Value;
                        SyncEntity.Update(map, SyncSettings.SrcDbConnectionString);
                    }
                }
                catch(Exception e)
                {
                    throw e;
                }

                return result;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return null;
        }

        public String DeploySource(long id)
        {
            var rep = GetRepository();
            var entity = rep.FindByIdWithRef(id);

            GhostTableSync sync = GetGhostTableSync(1000);
            sync.CreateGhostInt(entity, true);

            return null;
        }

        public String DeployDestination(long id)
        {
            var rep = GetRepository();
            var entity = rep.FindByIdWithRef(id);

            GhostTableSync sync = GetGhostTableSync(1000);
            sync.CreateDestinationInt(entity);

            entity.DeployDestinationDat = DateTime.Now;
            rep.Update(entity);

            return null;
        }

        public String DeleteSyncEntity(long id)
        {
            var rep = GetRepository();
            var entity = rep.FindByIdWithRef(id);
            if (entity != null)
            {
                rep.Delete(entity);
            }
            return null;
        }

        public String DeploySourceEnvironment()
        {
            GhostTableSync sync = GetGhostTableSync(1000);
            sync.CreateSourceEnvironment();

            return null;
        }

        public String DeployDestEnvironment()
        {
            GhostTableSync sync = GetGhostTableSync(1000);
            sync.CreateDestEnvironment();

            return null;
        }

        public SyncEntity ImportSchema(long id, short type)
        {
            var rep = GetRepository();
            var schemaEntity = rep.SchemaFindById(id, type);
            var syncEntity = rep.FindBySourceTableName(schemaEntity.Name, true);

            if (syncEntity == null)
            {
                syncEntity = new SyncEntity();

                syncEntity.Name = schemaEntity.Name;
                syncEntity.SourceTableName = schemaEntity.Name;
                syncEntity.DestinationTableName = schemaEntity.Name;
                syncEntity.ShadowTableName = "q_" + schemaEntity.Name + "_shadow";
                syncEntity.SyncEnabledBool = false;

                rep.Insert(syncEntity);
                // hur får jag tag i dess id?????
                // gör insert i databasen
            }

            // gå igenom alla kolumner i tabellen
            foreach (SyncEntityColumn col in schemaEntity.Columns)
            {
                SyncEntityColumn currentCol = syncEntity.Columns.Where(c => c.ColumnName == col.ColumnName).FirstOrDefault();
                if (currentCol != null)
                {
                    // den fanns redan, men importera denna kolumn igen
                    currentCol.Import(col);
                    currentCol.SyncEntityId = syncEntity.Id;

                }
                else
                {
                    // den fanns inte, importera denna kolumn
                    currentCol = new SyncEntityColumn();
                    currentCol.Import(col);
                    currentCol.SyncEntityId = syncEntity.Id;
                    //currentCol.SyncEntity = syncEntity;
                    syncEntity.Columns.Add(currentCol);
                }
            }

            syncEntity.ImportDat = DateTime.Now;
            rep.Update(syncEntity);
            return syncEntity;
        }

        public SyncEntity GetSchemaEntity(long id, short type)
        {
            try
            {
                Console.WriteLine("GetEntities");
                SyncEntity e = GetRepository().SchemaFindById(id, type);
                return e;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return null;

        }


        public List<SyncEntity> GetSchemaEntities()
        {
            try
            {
                Console.WriteLine("GetEntities");
                List<SyncEntity> list = GetRepository().SchemaFindAll();
                return list;

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return null;

        }

        public bool ToggleSyncEnabled(long id)
        {
            var rep = GetRepository();
            SyncEntity entity = rep.SyncEntity_FindById(id);

            entity.SyncEnabledBool = !entity.SyncEnabledBool;
            rep.Update(entity);

            return entity.SyncEnabledBool;
        }

        public bool ToggleSyncColumnEnabled(long id)
        {
            var rep = GetRepository();
            SyncEntityColumn col = rep.SyncEntityColumn_FindById(id);

            col.SyncEnabledBool = !col.SyncEnabledBool;
            rep.Update(col);

            return col.SyncEnabledBool;
        }

        public void Update(SyncEntity entity)
        {
            Console.WriteLine("Update");
            //SyncEntity e = (new SyncEntityDemoRepository()).GetSyncEntity();
            GetRepository().Update(entity);
        }

        public List<SyncEntity> GetEntities()
        {
            try
            {
                Console.WriteLine("GetEntities");
                // List<SyncEntity> list = (new SyncEntityDemoRepository()).GetSyncEntityList();
                List<SyncEntity> list = GetRepository().FindAll();
                return list;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return null;
        }

        public SyncEntity GetEntityByName(string name)
        {
            Console.WriteLine("GetEntityByName");
            //SyncEntity e = (new SyncEntityDemoRepository()).GetSyncEntity();
            SyncEntity e = GetRepository().FindByIdWithRef(1);
            return e;
        }

        public SyncEntity GetEntityById(long id)
        {
            Console.WriteLine("GetEntityById");
            //SyncEntity e = (new SyncEntityDemoRepository()).GetSyncEntity();
            SyncEntity e = GetRepository().FindByIdWithRef(id);
            return e;
        }

        public SyncEntityRepository GetRepository()
        {
            //string connectionStr__ = "Data Source=runner2.systeamportal.se;Initial Catalog=rick_nop22;User ID=evolution;Password=sVef#hu8;MultipleActiveResultSets=True";

            //string connectionStr = @"Data Source=ntalp7;Initial Catalog=ALP1;User ID=sa;Password=as;MultipleActiveResultSets=True";
            //string connectionStr = @"Data Source=172.31.6.46;Initial Catalog=PMTestBO;User ID=PMTestBO_user;Password=PMTestBO_user123!;MultipleActiveResultSets=True";
            //string connectionStr = @"data source=.\SQLEXPRESS;Initial Catalog=SyncTestSource;persist security info=True;Integrated Security=SSPI"; // Chanan

            //string connectionStr = ConfigurationManager.ConnectionStrings["SyncSourceDB"].ConnectionString;
            string connectionStr = SyncSettings.SrcDbConnectionString;

            SyncEntityRepository dal = new SyncEntityRepository();
            dal.ConnectionString = connectionStr;
            dal.DataProvider = new SqlDataProvider();
            return dal;
        }

        private static DateTimeTableSync GetDateTimeTableSync(int batchSize)
        {
            DateTimeTableSync sync = new DateTimeTableSync();
            sync.BatchSize = batchSize;
            sync.SourceConnectionString = SyncSettings.SrcDbConnectionString;
            sync.DestinationConnectionString = SyncSettings.DestDbConnectionString;
            sync.sourceDataProvider = new SqlDataProvider();
            sync.destinationDataProvider = new SqlDataProvider();
            sync.sqlBuilder = new SqlBuilder();
            return sync;
        }


        private static GhostTableSync GetGhostTableSync(int batchSize)
        {
            GhostTableSync sync = new GhostTableSync();
            sync.BatchSize = batchSize;
            sync.SourceConnectionString = SyncSettings.SrcDbConnectionString;
            sync.DestinationConnectionString = SyncSettings.DestDbConnectionString;
            sync.sourceDataProvider = new SqlDataProvider();
            sync.destinationDataProvider = new SqlDataProvider();
            sync.sqlBuilder = new SqlBuilder();
            return sync;
        }

    }*/
}
